<?php
namespace app\common\lib\module_config\tagsconfig;

use app\common\lib\model_operate\QueryDevice;
use app\common\lib\model_operate\Tools;
use app\common\lib\module_config\FormCtrl;
use app\common\lib\module_config\TagsConfig;
use think\Db;

class Edit extends TagsConfig
{
    private $base; //主表信息

    private $where; //主表信息

    public function __construct($trace, $tags)
    {
        parent::__construct($trace, $tags);

        //设置主表信息
        $this->setBase();
    }

    /**
     * 设置主表信息
     */
    private function setBase()
    {
        if(!empty($this->config['database'])){
            $this->base['tableName'] = Tools::tableNameFormat($this->config['database'], 1);
        }else{
            $this->base['tableName'] = Tools::tableNameFormat($this->trace->getApp(), 1);
        }

        //获取主表字段
        $this->base['tableInfo']     = DB::getTableInfo($this->base['tableName']);
        $this->base['displayFields'] = [];
    }

    /**
     * 获取主表信息
     */
    public function getBase()
    {
        return $this->base;
    }

    public function createQuery()
    {
        return '子类 Add 实现的获取数据方法';
    }

    /**
     * 获取主键
     */
    public function getPk()
    {
        $pk = $this->base['tableInfo']['pk'];

        return $pk;
    }

    /**
     * 创建分离引入html的html
     */
    public function createArrayhtml($list = [])
    {
        //实例化控件生成类
        $fo = new FormCtrl($this->trace, $this->tags);

        $fo->setList($list);
        
        $html = '';

        $fo->setList($list);

        if (empty($this->config['fields'])) {
            return '';
        }
        $da = [];
        $i  = 0;

        $this->transformshow($list);
        //非引入html控件
        //引入和非引入拆成数组
        foreach ($this->config['fields'] as $key => $value) {

            //判断是否是引入html
            if ($value['ctrl_type'] == 'htmlpage' && $value['is_show'] == 1 && !empty($value['html'])) {
                if (empty($da[$i])) {
                    $da[$i] = $fo->setHtmlpage($value);
                    $i++;
                } else {
                    $i++;
                    $da[$i] = $fo->setHtmlpage($value);
                }
                continue;
            }

            if (!in_array($value['field'], array_keys($list))) {
                continue;
            }
            //show_type 1.查表 2.固定内容 3.多选项
            if ($value['show_type'] == 1) {
                $value['option'] = $this->selectGetTableData($value['option']);
            } elseif ($value['show_type'] == 2) {
                $value['option'] = json_decode($value['option'], true);
            } elseif ($value['show_type'] == 3) {
                $value['option'] = json_decode($value['option'], true);
            }

            $value['default'] = $list[$value['field']];
            //add中如果隐藏，避免添加时报错，生成一个隐藏input
            if ($value['is_show'] == 1) {
                $html .= $fo->setHtml($value);
            } else {
                //设置主键
                if ($value['field'] == $this->getPk()) {
                    $html .= $fo->setHidden($value);
                }
            }

            if (empty($da[$i])) {
                $da[$i] = $html;

            } else {
                $da[$i] = $html;
                // $da[$i] = $da[$i].$html;
            }

        }

        // return $html;
        return $da;
    }

    /**
     * 生成html
     */
    public function createHtml($list = [])
    {
        $fo = new FormCtrl($this->trace, $this->tags);

        $fo->setList($list);

        $html = '';

        if (empty($this->config['fields'])) {
            return '';
        }

        $this->transformshow($list);

        foreach ($this->config['fields'] as $key => $value) {

            // if (!in_array($value['field'], array_keys($list))) {
            //     continue;
            // }

            // if(!empty($value['permission']) && $value['permission'] == '1'){
            //     //检查权限
            //     $check = ( new \plugins\store\Common )->getAllowAccess();
            //     if($check === true){
                    
            //     }else{
            //         continue;
            //     }
            // }   

            if ($value['show_type'] == 1) {
                if ($value['is_show'] == 2) {
                    continue;
                }
                $value['option'] = $this->selectGetTableData($value['option']);
            } elseif ($value['show_type'] == 2) {
                $value['option'] = json_decode($value['option'], true);
            } elseif ($value['show_type'] == 3) {
                $value['option'] = json_decode($value['option'], true);
            }

            $value['default'] = (!in_array($value['field'], array_keys($list))) ? '' : $list[$value['field']];

            if ($value['is_show'] == 1) {
                $html .= $fo->setHtml($value);
            } else {
                //设置主键
                if ($value['field'] == $this->getPk()) {
                    $html .= $fo->setHidden($value);
                }
            }
        }
        return $html;
    }

    /**
     * 数据处理
     */
    public function transformshow(&$list)
    {

        $config = $this->config['fields'];

        unset($list['_plugin'], $list['_controller'], $list['_action']);

        foreach ($list as $key => $value) {

            if (empty($config[$key])) {
                continue;
            }

            switch ($config[$key]['ctrl_type']) {
                case 'date':
                    $list[$key] = date('Y-m-d H:i:s', $list[$key]);
                    break;
                case 'checkbox':
                    $list[$key] = json_decode($list[$key], true);
                    break;
                case 'moreimage':
                    $list[$key] = json_decode($list[$key], true);
                    break;
                case 'ueditor':
                    $list[$key] = autoHtmlspecialcharsDecode($list[$key]);
                    break;
                default:
                    # code...
                    break;
            }
        }

        return $list;
    }

    /**
     * 查表显示数据
     */
    private function selectGetTableData($option)
    {
        $da     = [];

        $option = json_decode($option, true);
        if (!empty($option) && count($option) == 3) {
            list($table, $fields, $items) = $option;
            $table                        = Tools::tableNameFormat($table);
            $tb                           = Db::name($table)->field($fields)->select()->toArray();
            foreach ($items as $key => $value) {
                if (false === strpos($key, '$') && false === strpos($value, '$')) {
                    $da[$key] = $value;
                } else {
                    $ik = str_replace("$", '', $key);
                    $iv = str_replace("$", '', $value);
                    $a  = array_column($tb, $iv, $ik);
                    $da = $da + $a;
                }
            }
        }
        return $da;
    }

    /**
     * 执行修改
     */
    public function saveEdit($param)
    {
        $base = $this->base;

        $pk = $base['tableInfo']['pk'];

        if(!empty($this->config['database'])){
            $module_name = $this->config['database'];
        }else{
            $module_name = $this->trace->getApp();
        }

        $where = [$pk => $param[$pk]];

        $str = 'plugins\\' . $this->trace->getApp() . '\\model\\' . cmf_parse_name($module_name, 1) . 'Model';
        // $str = 'plugins\\' . $module_name . '\\model\\' . cmf_parse_name($module_name, 1) . 'Model';

        $model = new $str();


        $rs = $this->transform($param, $model);


        if ($rs['status'] !== true) {
            return $rs;
        }

        // try {
            $result = $model->allowField(true)->update($param, $where, true);
            
            $res = $this->saveRelevancePage($model, $param);
            if (isset($res['status']) && $res['status'] != 'success') {
                return ['status' => false, 'message' => $res['message'], 'code' => 101, 'data' => null];
            }

            $pk = $this->getPk();
            return ['status' => true, 'message' => '修改成功', 'code' => 200, 'data' => $param[$pk]];
        // } catch (\Exception $e) {
        //     return ['status' => false, 'message' => '修改失败', 'code' => 106];
        // }
    }

    /**
     * 获取模块中html.json文件
     */
    public function getHtmlConfig()
    {
        $module_name = $this->trace->getApp();

        $res = getModuleConfig($module_name, 'config', 'html.json');

        $res = json_decode($res, true);

        if (!empty($res['html'])) {

            return $res['html'];
        }

        return $res;
    }

    /**
     * 保存关联页面
     */
    public function saveRelevancePage(&$model, &$param)
    {
        //获取配置信息
        $config = $this->config['fields'];

        //获取tag
        $tag = $this->tags;

        //获取引入的
        $html_configs = $this->getHtmlConfig();

        $search = 'htmlpage';
        foreach ($config as $key => $value) {
            if ($value['ctrl_type'] != 'htmlpage' || $value['is_show'] != 1) {
                continue;
            }

            $search      = $value['html'];
            $html_config = array_filter($html_configs, function ($t) use ($search) {return $t['name'] == $search;});

            //执行添加
            if (empty($html_config)) {
                continue;
            }

            $html_config = array_values($html_config)[0];

            if (empty($html_config[$tag]['save'])) {
                continue;
            }

            $save = $html_config[$tag]['save'];

            if (empty($save['controller'])) {
                continue;
            }

            $cto   = explode('@', $save['controller']);
            $class = $cto[0];
            $func  = $cto[1];

            //判断类是否定义
            if (!class_exists($class)) {
                return zy_sys_echo(false, $class . '类未定义,不能生辰html', null, 101);
            }

            $class = '\\' . $class;

            $cls = new $class();

            //判断类方法是否定义
            if (!method_exists($class, $func)) {
                return zy_sys_echo(false, $class . '类中' . $func . '方法未定义', null, 101);
            }

            //获取要传的字段
            if (!empty($save['field'])) {
                $field = $param[$save['field']];
            } else {
                $field = '';
            }

            if (isset($param[$value['field']])) {
                $pa = $param[$value['field']];
            } else {
                $pa = [];
            }

            // $pa = $param[$value['field']];
           
            //第一个字段传数据
            $html = $cls->$func($pa, $field);

            return $html;
        }
    }


    /**
     * 保存添加时数据处理
     */
    public function transform(&$param, &$model)
    {

        $config = $this->config['fields'];
        unset($param['_plugin'], $param['_controller'], $param['_action']);
        $pk = $model->getPk();

        foreach ($config as $key => $value) {
            //字段为空判断
            if (isset($value['is_required']) && $value['is_required'] == 1) {
                if (empty($param[$key])) {
                    return ['status' => false, 'message' => $value['title'] . '不能为空', 'code' => 106];
                }
            } 
            if (empty($param[$key])) {
                continue;
            }

            //判断唯一字段
            if ($value['is_sole'] == 1) {
                $res = $model->get([ 
                    $key => $param[$key],
                    $pk  => ['<>', $param[$pk]]
                ]);


                if (!empty($res)) {
                    return ['status' => false, 'message' => $value['title'] . '已存在', 'code' => 105];
                }
            }
            
            switch ($value['ctrl_type']) {
                case 'date':
                    $param[$key] = strtotime($param[$key]);
                    break;
                case 'checkbox':
                    $param[$key] = json_encode($param[$key], JSON_UNESCAPED_UNICODE);
                    break;
                case 'moreimage':
                    $param[$key] = json_encode($param[$key], JSON_UNESCAPED_UNICODE);
                    break;
                case 'htmlpage':

                    $rs = $this->yrhtmlisNull($value['html']);
                    //如果为空
                    if ($rs == true) {
                        //如果不是字符串
                        if (!is_string($param[$key])) {
                            $param[$key] = json_encode($param[$key], JSON_UNESCAPED_UNICODE);
                        }
                    }
                    break;
                case 'ueditor':
                    $param[$key] = autoHtmlspecialcharsDecode($param[$key]);
                    break;
                default:
                    
                    break;
            }
        }

        return ['status' => true, 'message' => 'success', 'code' => 200];
    }

    // /**
    //  * 数据处理
    //  */
    // public function transform(&$param, &$model)
    // {

    //     $config = $this->config['fields'];

    //     unset($param['_plugin'], $param['_controller'], $param['_action']);

    //     $pk = $model->getPk();

    //     foreach ($param as $key => $value) {

    //         if (empty($config[$key])) {
    //             continue;
    //         }

    //         //判断唯一字段
    //         if ($config[$key]['is_sole'] == 1) {
    //             $res = $model->get([$key => ['=', $value], $pk => ['<>', $param[$pk]]]);

    //             if (!empty($res)) {
    //                 return ['status' => false, 'message' => $config[$key]['title'] . '已存在', 'code' => 105];
    //             }
    //         }

    //         switch ($config[$key]['ctrl_type']) {
    //             case 'date':
    //                 $param[$key] = strtotime($param[$key]);
    //                 break;
    //             case 'checkbox':
    //                 $param[$key] = json_encode($param[$key], JSON_UNESCAPED_UNICODE);
    //                 break;
    //             case 'moreimage':
    //                 $param[$key] = json_encode($param[$key], JSON_UNESCAPED_UNICODE);
    //                 break;
    //             case 'htmlpage':
    //                 $rs = $this->yrhtmlisNull($config[$key]['html']);
    //                 //如果为空
    //                 if ($rs == true) {
    //                     //如果不是字符串
    //                     if (!is_string($param[$key])) {
    //                         $param[$key] = json_encode($param[$key], JSON_UNESCAPED_UNICODE);
    //                     }
    //                 }
    //                 break;
    //             case 'ueditor':
    //                 $param[$key] = autoHtmlspecialcharsDecode($param[$key]);
    //                 break;
    //             default:
    //                 # code...
    //                 break;
    //         }
    //     }

    //     return ['status' => true, 'message' => 'success', 'code' => 200];
    // }

    //引入html中的save的controller 是否为空
    public function yrhtmlisNull($ht)
    {
        $config = $this->config['fields'];

        $html_configs = $this->getHtmlConfig();
        //获取tag
        $tag = $this->tags;

        $html_config = array_filter($html_configs, function ($t) use ($ht) {return $t['name'] == $ht;});

        $html_config = array_values($html_config)[0];

        if (empty($html_config[$tag]['save']['controller'])) {
            return true;
        }

        return false;
    }

    /**
     * 获取搜索参数的条件
     */
    public function getWhere()
    {
        return $this->where;
    }

    /**
     * 执行查询
     */
    public function query()
    {

        $type = (isset($this->relevance['relevanceType']['queryType']) && !empty($this->relevance['relevanceType']['queryType'])) ? $this->relevance['relevanceType']['queryType'] : 'Single';
        return QueryDevice::createQuery($this, $type);
    }

    public function setParam()
    {
        return true;
    }

}
